package com.betterjr.modules.risk.loan.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.betterjr.common.selectkey.SerialGenerator;
import com.betterjr.common.service.BaseService;
import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.Collections3;
import com.betterjr.common.utils.QueryTermBuilder;
import com.betterjr.modules.agreement.data.ScfElecAgreementInfo;
import com.betterjr.modules.agreement.service.ScfElecAgreementService;
import com.betterjr.modules.document.ICustFileService;
import com.betterjr.modules.risk.loan.dao.LoanProjectElcAgreementMapper;
import com.betterjr.modules.risk.loan.data.FillAgreementFactory;
import com.betterjr.modules.risk.loan.data.LoanProjectElcAgreementConstantCollections;
import com.betterjr.modules.risk.loan.data.LoanProjectRelationConstantCollections;
import com.betterjr.modules.risk.loan.data.LoanTransactionRelationConstantCollections;
import com.betterjr.modules.risk.loan.entity.LoanProjectElcAgreement;
import com.betterjr.modules.risk.loan.entity.LoanProjectRelation;
import com.google.common.collect.Lists;

@Service
public class LoanProjectElcAgreementService
        extends BaseService<LoanProjectElcAgreementMapper, LoanProjectElcAgreement> {

    @Reference(interfaceClass = ICustFileService.class)
    private ICustFileService custFileDubboService;

    @Autowired
    private ScfElecAgreementService elcAgreementSourceService;

    /**
     * 
     * @Title: queryElcAgreement 
     * @Description: 查询贷款项目下面的电子合同
     * @param anLoanId  贷款项目id
     * @param anType 电子合同类型  1:账户监管 2 平台服务协议  3确权协议 4 其他协议
     * @return TODO(说明)
     * @throws 
     * @author xuyp
     * @date 2018年6月27日 下午3:46:09
     */
    @SuppressWarnings("unchecked")
    public List<LoanProjectElcAgreement> queryElcAgreement(Long anLoanId, String anType) {

        List<LoanProjectElcAgreement> elcAgreements = Lists.newArrayList();

        if (anLoanId != null && anLoanId != 0L) {

            Map<String, Object> map = QueryTermBuilder.newInstance()
                    .put("businStatus", LoanTransactionRelationConstantCollections.RELATIONS_BUSINSTATUS_OK)
                    .put("loanId", anLoanId).build();
            if (StringUtils.isNoneBlank(anType)) {
                map.put("type", anType.split(LoanProjectRelationConstantCollections.FILE_DATA_SEPATORY_CHAR));
            }

            return this.selectByProperty(map, "id Desc");

        }

        return elcAgreements;

    }

    /**
     * 
     * @Title: saveOrUpdateElcAgreement 
     * @Description: 通过贷款项目新增或者修改电子合同
     * @param anRelation
     * @return 
     * @throws 
     * @author xuyp
     * @date 2018年6月27日 下午5:32:47
     */
    public List<LoanProjectElcAgreement> saveOrUpdateElcAgreement(LoanProjectRelation anRelation) {

        ArrayList<LoanProjectElcAgreement> newArrayList = Lists.newArrayList();

        if (anRelation != null && anRelation.getId() != null) {

            // 账户监管合同
            if (anRelation.getAccountRegulatoryAgreement() != null)
                newArrayList.add(this.saveOrUpdateElcAgreement(anRelation.getAccountRegulatoryAgreement()));

            // 数据确权协议
            if (anRelation.getDataConfirmationAgreement() != null)
                newArrayList.add(this.saveOrUpdateElcAgreement(anRelation.getDataConfirmationAgreement()));

            // 平台服务费协议
            if (anRelation.getPlatformServiceAgreement() != null)
                newArrayList.add(this.saveOrUpdateElcAgreement(anRelation.getPlatformServiceAgreement()));

            if (!Collections3.isEmpty(anRelation.getOtherAgreements())) {
                List<LoanProjectElcAgreement> others = queryElcAgreement(anRelation.getId(),
                        LoanProjectElcAgreementConstantCollections.ELCAGREEMENT_TYPE_OTHERAGREEMENTS);
                for (LoanProjectElcAgreement loanProjectElcAgreement : others) {
                    if (loanProjectElcAgreement != null) this.deleteByPrimaryKey(loanProjectElcAgreement);
                }
                for (LoanProjectElcAgreement loanProjectElcAgreement : anRelation.getOtherAgreements()) {
                    if (loanProjectElcAgreement != null) {

                        this.insertSelective(loanProjectElcAgreement);
                        newArrayList.add(loanProjectElcAgreement);
                    }
                }
            }

        }

        return newArrayList;

    }

    /**
     * 
     * @Title: saveOrUpdateElcAgreement 
     * @Description: 新增或者修改电子合同 
     * @param anAgreement
     * @return 
     * @throws 
     * @author xuyp
     * @date 2018年6月27日 下午5:33:34
     */
    private LoanProjectElcAgreement saveOrUpdateElcAgreement(LoanProjectElcAgreement anAgreement) {

        if (anAgreement != null && anAgreement.getLoanId() != null && anAgreement.getLoanId() != 0l
                && StringUtils.isNoneBlank(anAgreement.getType())) {

            List<LoanProjectElcAgreement> elcAgreement = queryElcAgreement(anAgreement.getLoanId(),
                    anAgreement.getType());

            for (LoanProjectElcAgreement loanProjectElcAgreement : elcAgreement) {
                this.deleteByPrimaryKey(loanProjectElcAgreement);
            }
        }

        if (anAgreement.getId() == null || anAgreement.getId() == 0l) {
            anAgreement.saveAddInitValue();
        }

        if (anAgreement != null) this.insertSelective(anAgreement);

        return anAgreement;
    }

    /**
     * 
     * @Title: saveUnfriendLoan 
     * @Description: 解除和贷款项目的绑定关系
     * @param anLoan
     * @param ids  合同主键ids  排除不解绑的合同主键
     * @return TODO(说明)
     * @throws 
     * @author xuyp
     * @date 2018年6月27日 下午6:52:57
     */
    public List<LoanProjectElcAgreement> saveUnfriendLoan(Long anLoan, String ids) {

        if (anLoan != null && anLoan != 0L) {

            List<LoanProjectElcAgreement> lists = queryElcAgreement(anLoan, "");

            for (LoanProjectElcAgreement agreement : lists) {
                if (!ids.contains(agreement.getId() + "")) {

                    agreement.setBusinStatus(LoanTransactionRelationConstantCollections.RELATIONS_BUSINSTATUS_DELETED);
                    this.updateByPrimaryKeySelective(agreement);
                }
            }

            return lists;
        }

        return Lists.newArrayList();
    }

    /**
     * 
     * @Title: saveAddAgreement 
     * @Description: 新增电子合同  只做新增电子合同，不绑定贷款项目的关系
     * @param agreement
     * @return TODO(说明)
     * @throws 
     * @author xuyp
     * @date 2018年7月2日 上午9:36:57
     */
    public LoanProjectElcAgreement saveAddAgreement(LoanProjectElcAgreement agreement) {

        BTAssert.notNull(agreement, "对象不能为空");

        checkAgreement(agreement);

        agreement.saveAddInitValue();
        agreement.setLoanId(null);
        /*if (agreement.getId() == null || agreement.getId() == 0l) {
            if (agreement.getLoanId() != null || agreement.getLoanId() != 0l) {
                List<LoanProjectElcAgreement> elcAgreement = this.queryElcAgreement(agreement.getLoanId(),
                        agreement.getType());
                if (!Collections3.isEmpty(elcAgreement)) {
                    agreement.setId(Collections3.getFirst(elcAgreement).getId());
                    for (LoanProjectElcAgreement loanProjectElcAgreement : elcAgreement) {
                        this.deleteByPrimaryKey(loanProjectElcAgreement);
                    }
                }
            }
        }*/

        if (LoanProjectElcAgreementConstantCollections.ELCAGREEMENT_SUBTYPE_UNDERLINE.equals(agreement.getSubType())) {

            if (agreement.getBatchNo() == null || agreement.getBatchNo() == 0l) {
                agreement.setBatchNo(custFileDubboService.updateAndDelCustFileItemInfo(agreement.getFileId() + "",
                        agreement.getBatchNo()));
            }

        }

        this.insertSelective(agreement);

        return agreement;

    }

    /**
     * 
     * @Title: saveBindRelationAgreement 
     * @Description: 绑定贷款项目和电子合同关系
     * @param anLoan
     * @param agreementIds
     * @return TODO(说明)
     * @throws 
     * @author xuyp
     * @date 2018年7月2日 上午10:38:55
     */
    @SuppressWarnings("unchecked")
    public LoanProjectRelation saveBindRelationAgreement(LoanProjectRelation anLoan, String agreementIds) {

        if (anLoan != null && StringUtils.isNoneBlank(agreementIds)) {

            // 首先解绑原来的信息
            saveUnfriendLoan(anLoan.getId(), agreementIds);

            String[] aggrementArr = agreementIds.split(LoanProjectRelationConstantCollections.FILE_DATA_SEPATORY_CHAR);

            Long[] ids = new Long[aggrementArr.length];

            for (int i = 0; i < aggrementArr.length; i++) {
                try {
                    ids[i] = Long.parseLong(aggrementArr[i]);

                }
                catch (Exception e) {
                    BTAssert.notNull(null, "转换合同id异常" + aggrementArr[i]);
                }
            }

            Map<String, Object> map = QueryTermBuilder.newInstance().put("id", ids)
                    .put("businStatus", LoanTransactionRelationConstantCollections.RELATIONS_BUSINSTATUS_OK).build();
            List<LoanProjectElcAgreement> list = this.selectByProperty(map, "id desc");

            if (!Collections3.isEmpty(list)) {
                fillAgreementLoanProject(anLoan, list);
            }

            for (LoanProjectElcAgreement loanProjectElcAgreement : list) {
                this.updateByPrimaryKeySelective(loanProjectElcAgreement);
            }

        }
        return anLoan;

    }

    /**
     * 
     * @Title: fillAgreementLoanProject 
     * @Description: 封装电子合同和贷款项目信息 
     * @param anLoan
     * @param list 
     * @throws 
     * @author xuyp
     * @date 2018年7月2日 上午10:44:24
     */
    private void fillAgreementLoanProject(LoanProjectRelation anLoan, List<LoanProjectElcAgreement> list) {

        if (anLoan != null && !Collections3.isEmpty(list)) {

            FillAgreementFactory.invoke(anLoan, list);
            for (LoanProjectElcAgreement loanProjectElcAgreement : list) {
                loanProjectElcAgreement
                        .setBusinStatus(LoanTransactionRelationConstantCollections.RELATIONS_BUSINSTATUS_OK);
                loanProjectElcAgreement.setLoanId(anLoan.getId());

            }

        }

    }

    private void checkAgreement(LoanProjectElcAgreement agreement) {

        BTAssert.isTrue(StringUtils.isNoneBlank(agreement.getType()), "电子合同类型不能为空");
        BTAssert.isTrue(StringUtils.isNoneBlank(agreement.getSubType()), "电子合同类型不能为空");
        BTAssert.isTrue(StringUtils.isNoneBlank(agreement.getAggrementName()), "协议名称不能为空");

        if (LoanProjectElcAgreementConstantCollections.ELCAGREEMENT_SUBTYPE_ONLINE.equals(agreement.getSubType())) {
            BTAssert.notNull(agreement.getContractTemplateId(), "请选择合同模版");
            BTAssert.notNull(agreement.getBatchNo(), "请选择合同模版");
        } else {
            BTAssert.isTrue(StringUtils.isNoneBlank(agreement.getFileName()), "请上传附件");
            BTAssert.notNull(agreement.getFileId(), "请上传附件");
        }

    }

    /**
     * 
     * @Title: checkElcAgreementBusinStatus 
     * @Description: 校验电子合同状态  如果还有未签署完成的电子合同返回true     全部签署完成返回false
     * @param anLoanId
     * @return 
     * @throws 
     * @author xuyp
     * @date 2018年7月3日 上午9:34:49
     */
    public void checkNoSignElcAgreements(Long anLoanId) {

        List<ScfElecAgreementInfo> lists = elcAgreementSourceService.queryNoSignElcAgreementByRequstNo(anLoanId + "",
                "11,12,13,14");

        for (ScfElecAgreementInfo scfElecAgreementInfo : lists) {
            if ("11".equals(scfElecAgreementInfo.getAgreeType())) BTAssert.notNull(null, "确权协议尚未签署完成");
            if ("12".equals(scfElecAgreementInfo.getAgreeType())) BTAssert.notNull(null, "账户监管协议尚未签署完成");
            if ("13".equals(scfElecAgreementInfo.getAgreeType())) BTAssert.notNull(null, "平台服务费协议尚未签署完成");
            if ("11".equals(scfElecAgreementInfo.getAgreeType())) BTAssert.notNull(null, "其他协议尚未签署完成");
        }

    }

}
